/**
 * @(#) StructArrayTypeHandler.java
 * @Package ls.cis.mb.ca.acct.manualopt.service
 * <p>
 * Copyright © Longshine Corporation. All rights reserved.
 */

package ls.cis.mb.ca.pay.bankcollection.controller;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 类描述：
 *
 * @version $Id: StructArrayTypeHandler.java,v 1.3 2023/11/16 13:30:27 40250 Exp $
 * <p>
 * History:  2015-3-21 下午2:38:56   lvj   Created.
 * @author: lvj
 */
public class StructArrayTypeHandler extends BaseTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        Connection connection = preparedStatement.getConnection();
        if (parameter instanceof List) {
            List<Struct> list = new ArrayList<>();
            for (Object[] o : (List<Object[]>) parameter) {
                if (o != null && o.length != 0) {
                    int length = o.length;
                    for (int j = 0; j < length; j++) {
                        if (o[i] != null) {
                            String line = (String) o[i];
                            String[] split = line.split("\\|");
                            if (split.length < 8) {
                                split = Arrays.copyOf(split, 8);
                            }
                            Struct struct = connection.createStruct("typ_collection_check", split);
                            list.add(struct);
                        }
                    }
                }
            }
            Array array = connection.createArrayOf("typ_collection_check_array", list.toArray());
            preparedStatement.setArray(i, array);
        }
    }

    @Override
    public Object getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return getArray(resultSet.getArray(columnName));
    }

    public Object getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return getArray(resultSet.getArray(columnIndex));
    }

    @Override
    public Object getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return getArray(callableStatement.getArray(columnIndex));
    }

    private Object[] getArray(Array array) {
        if (array == null) {
            return null;
        }

        try {
            return (Object[]) array.getArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
